package whf.framework.web.init;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import whf.framework.entity.AbstractEntity;
import whf.framework.exception.FindException;
import whf.framework.exception.ServiceNotFoundException;
import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.meta.Meta;
import whf.framework.meta.MetaFactory;
import whf.framework.service.QueryService;
import whf.framework.util.BeanFactory;
import whf.framework.util.BeanUtils;
import whf.framework.util.TypeUtils;

/**
 * @author wanghaifeng
 *
 */
public class PrepareData {
	private static Log log = LogFactory.getLog(PrepareData.class);
	
	private Meta meta;

	/**
	 * Key: propertyName
	 * Value: List data
	 */
	private Map<String, List> data = new HashMap<String, List>();
	
	/**
	 * Key: propertyName
	 * Value: Search Condition String
	 */
	private Map<String, String> parameters = new HashMap<String, String>();

	public PrepareData(Meta meta, Map<String, String> parameters){
		this.meta = meta;
		this.parameters = parameters;
		this.prepare();
	}
	
	public PrepareData(Class modelClass, Map<String, String> parameters){
		this(MetaFactory.findByModelClass(modelClass), parameters);
	}
	
	/**
	 * 准备数据
	 * @modify wanghaifeng Aug 24, 2006 11:18:30 PM
	 */
	private void prepare(){
		PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(this.meta.getModelClass());
		for(int i=0;i<descriptors.length;i++){
			String propertyName = descriptors[i].getName();
			Class propertyType = descriptors[i].getPropertyType();
			if(!parameters.containsKey(propertyName)) continue;
			try{
				if(TypeUtils.isExtendsFrom(propertyType, AbstractEntity.class)){
					Meta meta = MetaFactory.findByModelClass(propertyType);
					QueryService qService = BeanFactory.getService(meta);
					String parameter = parameters.get(propertyName);
					if(parameter == null) parameter = "";
					List list = qService.query(parameter);
					data.put("Property-"+propertyName, list);
				}
			}catch(ServiceNotFoundException e){
				log.warn(propertyType, e);
			}catch(FindException fe){
				log.error(this, fe);
			}
		}
	}
	
	public Map<String, List> getData(){
		return this.data;
	}
	
	public static void main(String[] args) throws Exception{
		new PrepareData(whf.framework.meta.entity.Object.class, null);
	}
}
